package com.warom.sdg.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.warom.sdg.database.SdgDatabase;
import com.warom.sdg.model.ThresholdSettingEntity;

import java.util.ArrayList;
import java.util.List;

/**
 * 阈值设置数据访问对象实现类
 */
public class ThresholdSettingDao_Impl extends ThresholdSettingDao {
    private static final String TAG = "ThresholdSettingDao";

    public ThresholdSettingDao_Impl(SdgDatabase dbHelper) {
        super(dbHelper);
    }

    @Override
    public List<ThresholdSettingEntity> getAll() {
        List<ThresholdSettingEntity> settings = new ArrayList<>();
        SQLiteDatabase db = null;
        Cursor cursor = null;

        try {
            db = dbHelper.getReadableDatabase();
            cursor = db.query(
                    SdgDatabase.TABLE_THRESHOLD_SETTINGS,
                    null,
                    null,
                    null,
                    null,
                    null,
                    SdgDatabase.COLUMN_PARAM_TYPE + " ASC"
            );

            if (cursor != null && cursor.moveToFirst()) {
                do {
                    ThresholdSettingEntity entity = cursorToEntity(cursor);
                    settings.add(entity);
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            Log.e(TAG, "获取所有阈值设置失败", e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return settings;
    }

    @Override
    public ThresholdSettingEntity getByParamType(String paramType) {
        ThresholdSettingEntity entity = null;
        SQLiteDatabase db = null;
        Cursor cursor = null;

        try {
            db = dbHelper.getReadableDatabase();
            cursor = db.query(
                    SdgDatabase.TABLE_THRESHOLD_SETTINGS,
                    null,
                    SdgDatabase.COLUMN_PARAM_TYPE + " = ?",
                    new String[]{paramType},
                    null,
                    null,
                    null
            );

            if (cursor != null && cursor.moveToFirst()) {
                entity = cursorToEntity(cursor);
            }
        } catch (Exception e) {
            Log.e(TAG, "根据参数类型获取阈值设置失败: " + paramType, e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return entity;
    }

    @Override
    public boolean upsert(ThresholdSettingEntity entity) {
        if (entity == null || entity.getParamType() == null || entity.getParamType().isEmpty()) {
            Log.e(TAG, "无法保存无效的阈值设置");
            return false;
        }

        Log.d(TAG, "尝试保存阈值设置: " + entity.toString());
        
        SQLiteDatabase db = null;
        boolean success = false;

        try {
            db = dbHelper.getWritableDatabase();
            db.beginTransaction();

            ContentValues values = entityToContentValues(entity);
            Log.d(TAG, "ContentValues: " + values.toString());
            
            // 设置更新时间
            long updateTime = System.currentTimeMillis();
            values.put(SdgDatabase.COLUMN_UPDATE_TIME, updateTime);
            Log.d(TAG, "设置更新时间: " + updateTime);

            // 检查记录是否存在
            ThresholdSettingEntity existingEntity = getByParamType(entity.getParamType());
            if (existingEntity != null) {
                Log.d(TAG, "找到现有记录，进行更新: " + existingEntity.toString());
                // 更新现有记录
                int rowsAffected = db.update(
                        SdgDatabase.TABLE_THRESHOLD_SETTINGS,
                        values,
                        SdgDatabase.COLUMN_PARAM_TYPE + " = ?",
                        new String[]{entity.getParamType()}
                );
                success = rowsAffected > 0;
                Log.d(TAG, "更新结果: " + (success ? "成功" : "失败") + ", 影响行数: " + rowsAffected);
            } else {
                Log.d(TAG, "未找到现有记录，进行插入");
                // 插入新记录
                long createTime = System.currentTimeMillis();
                values.put(SdgDatabase.COLUMN_CREATE_TIME, createTime);
                Log.d(TAG, "设置创建时间: " + createTime);
                
                long id = db.insert(SdgDatabase.TABLE_THRESHOLD_SETTINGS, null, values);
                success = id != -1;
                Log.d(TAG, "插入结果: " + (success ? "成功" : "失败") + ", 新ID: " + id);
            }

            if (success) {
                db.setTransactionSuccessful();
                Log.d(TAG, "事务提交成功");
            } else {
                Log.e(TAG, "操作失败，事务将回滚");
            }
        } catch (Exception e) {
            Log.e(TAG, "保存阈值设置失败", e);
            success = false;
        } finally {
            if (db != null) {
                db.endTransaction();
                Log.d(TAG, "事务结束");
            }
        }

        return success;
    }

    /**
     * 将Cursor转换为实体对象
     * @param cursor 数据库游标
     * @return 阈值设置实体
     */
    private ThresholdSettingEntity cursorToEntity(Cursor cursor) {
        ThresholdSettingEntity entity = new ThresholdSettingEntity();
        
        entity.setId(cursor.getLong(cursor.getColumnIndex(SdgDatabase.COLUMN_ID)));
        entity.setParamType(cursor.getString(cursor.getColumnIndex(SdgDatabase.COLUMN_PARAM_TYPE)));
        entity.setMinValue(cursor.getDouble(cursor.getColumnIndex(SdgDatabase.COLUMN_MIN_VALUE)));
        entity.setMaxValue(cursor.getDouble(cursor.getColumnIndex(SdgDatabase.COLUMN_MAX_VALUE)));
        entity.setUnit(cursor.getString(cursor.getColumnIndex(SdgDatabase.COLUMN_UNIT)));
        entity.setDescription(cursor.getString(cursor.getColumnIndex(SdgDatabase.COLUMN_DESCRIPTION)));
        entity.setCreateTime(cursor.getLong(cursor.getColumnIndex(SdgDatabase.COLUMN_CREATE_TIME)));
        entity.setUpdateTime(cursor.getLong(cursor.getColumnIndex(SdgDatabase.COLUMN_UPDATE_TIME)));
        
        return entity;
    }

    /**
     * 将实体对象转换为ContentValues
     * @param entity 阈值设置实体
     * @return ContentValues对象
     */
    private ContentValues entityToContentValues(ThresholdSettingEntity entity) {
        ContentValues values = new ContentValues();
        
        // 参数类型是必需的
        values.put(SdgDatabase.COLUMN_PARAM_TYPE, entity.getParamType());
        
        // 最小值和最大值
        values.put(SdgDatabase.COLUMN_MIN_VALUE, entity.getMinValue());
        values.put(SdgDatabase.COLUMN_MAX_VALUE, entity.getMaxValue());
        
        // 单位，如果为null则使用空字符串
        String unit = entity.getUnit();
        values.put(SdgDatabase.COLUMN_UNIT, unit != null ? unit : "");
        
        // 描述，如果为null则使用空字符串
        String description = entity.getDescription();
        values.put(SdgDatabase.COLUMN_DESCRIPTION, description != null ? description : "");
        
        return values;
    }
} 